package com.yyfax.ph.home.imageupload;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.AbsListView;
import android.widget.GridView;
import com.bumptech.glide.Glide;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.ph.R;
import com.yyfax.ph.base.PermissionActivity;
import com.yyfax.ph.base.dialog.DialogBase;
import com.yyfax.ph.common.imageselector.activity.PhotoSelectorActivity;
import com.yyfax.ph.common.imageselector.activity.PhotoViewActivity;
import com.yyfax.ph.common.imageselector.bean.ImageBean;

import java.util.ArrayList;
import java.util.List;

public class UploadImageActivity extends PermissionActivity implements UploadImagePresenter.View,
		ImageAdapter.ChooseUploadListener {
	private final static String TAG = "UploadImageActivity";

	private static final int LOADER_ID = 901;
	private static final int REQUEST_IMAGE = 0x0001;
	private static final int REQUEST_PERMISSION_READ_EXTERNAL_STORAGE = 0X0004;

	public static final String IMAGE_PATHS = "imagePaths";

	public static final String IMAGE_BEANS = "image_bean";

	public static final String UPLOAD_ARGUMENTS = "upload_arguments";
	public static final String BUNDLE_ARGUMENTS = "bundle_arguments";
	public static final String UPLOADING_FLAG = "uploading_flag";

	private ImageAdapter mImageAdapter;

	private UploadImagePresenter mPresenter;

	private List<String> mUploadImage = new ArrayList<>();//逐张上传

	boolean mOnActivityResult = false; //是否从onActivityResult返回来
	private boolean mUploading = false;//是否正在上传

	private ImageUploadArguments mArguments;//上传图片所传参数
	private int mPermissionRequestCodeExternalStorage = DEFAULT_PERMISSION_REQUEST_CODE_EXTERNAL_STORAGE;

	public static void start(Activity aty, Intent intent) {
		aty.startActivity(intent);
	}

	public static void startForResult(Activity aty, ImageUploadArguments arguments, int requestCode) {
		Intent intent = new Intent(aty, UploadImageActivity.class);
		CLog.i(TAG, "上传图片参数-11->" + arguments.toString());
		Bundle bundle = new Bundle();
		bundle.putParcelable(UPLOAD_ARGUMENTS, arguments);
		intent.putExtra(BUNDLE_ARGUMENTS, bundle);
		aty.startActivityForResult(intent, requestCode);
	}

	@Override
	public int getContentViewRes() {
		return R.layout.upload_image_activity_layout;
	}

	@Override
	public void initContentView() {
		super.initContentView();
		setBtnBackVisible(true);
		setTitleVisible(true);
		setTitle(mArguments.title);
		setTitleLeftVisible(false);
		setBtnRightVisible(false);
		findViewById(R.id.upload_layout).setOnClickListener(this);
		mImageAdapter = new ImageAdapter(this, this);
		((GridView) findViewById(R.id.upload_image_grid_view)).setAdapter(mImageAdapter);
		((GridView) findViewById(R.id.upload_image_grid_view)).setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {//停止滑动状态
					CLog.i(TAG, "上传图片 停止滑动-");
					Glide.get(UploadImageActivity.this).clearMemory();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

			}
		});
	}

	/**
	 * 基类onCreate()的时候调用
	 * 在BaseView之后预处理
	 */
	@Override
	public void pretreatmentAfterSetBaseView() {
		super.pretreatmentAfterSetBaseView();
		if (null == getIntent())
			return;
		Bundle bundle = getIntent().getBundleExtra(BUNDLE_ARGUMENTS);
		mArguments = bundle.getParcelable(UPLOAD_ARGUMENTS);
		CLog.i(TAG, "上传图片参数-22->" + mArguments.toString());
	}

	@Override
	public void onBackBtnPressed() {
		onBackPressed();
	}

	@Override
	public void onBackPressed() {
		if (mUploading) {
			showToast(R.string.exit_toast_uploading);
			return;
		}
		confirm();
	}

	@Override
	protected void onDestroy() {
		getSupportLoaderManager().destroyLoader(LOADER_ID);
		CLog.i(TAG, "lifecycle onDestroy()");
		super.onDestroy();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSupportLoaderManager().initLoader(LOADER_ID, null, this);
	}

	@Override
	protected void onStart() {
		super.onStart();
		CLog.i(TAG, "upload onStart()");
	}

	@Override
	protected void onStop() {
		super.onStop();
		Glide.get(this).clearMemory();
		CLog.i(TAG, "upload onStop()");
	}

	@Override
	protected void onResume() {
		super.onResume();
		CLog.i(TAG, "lifecycle onResume 刷新界面mImageBeans=" + mArguments.imageBeans.toString());
		if (mArguments.imageBeans.size() > 0 && !mOnActivityResult) {
			CLog.i(TAG, "lifecycle onResume 刷新界面mImageBeans=" + mArguments.imageBeans.toString());
			mImageAdapter.removeAll();
			mImageAdapter.addData(mArguments.imageBeans);
			mImageAdapter.notifyDataSetChanged();
		} else {
			mOnActivityResult = false;
		}
	}

	private void readBundle(Bundle savedInstanceState) {
		if (savedInstanceState != null) {
			mArguments = savedInstanceState.getParcelable(UPLOAD_ARGUMENTS);
			// TODO: 2017/5/12 恢复数据时上传中图片修改为上传失败
			if (savedInstanceState.getBoolean(UPLOADING_FLAG, false)) {
				for (ImageBean bean : mArguments.imageBeans) {
					if (ImageBean.STATUS_SUCCESS != bean.status) {
						bean.status = ImageBean.STATUS_FAIL;
					}
				}
				CLog.i(TAG, "lifecycle on reset status=" + mArguments.imageBeans.toString());
			}
			mImageAdapter.removeAll();
			mImageAdapter.addData(mArguments.imageBeans);
			mImageAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(this, new UploadImagePresenter.Generator());
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		mPresenter = (UploadImagePresenter) data;
		mPresenter.attach(this);
	}

	@Override
	public void onClick(View view) {
		super.onClick(view);
		switch (view.getId()) {
			case R.id.upload_layout:
				if (mUploading) {
					showToast(R.string.exit_toast_uploading);
					return;
				}
				confirm();
				break;
		}
	}

	/**
	 * 确认按钮点击触发
	 */
	public void confirm() {
		int size = mImageAdapter.getFailPathList().size();
		for (String filePath : mImageAdapter.getFailPathList()) {
			CLog.i(TAG, "失败图片filePath=" + filePath);
		}
		if (size > 0) {
			new DialogBase(this,
					getString(R.string.you_have_failed_uploded_failed_imags_strs, String.valueOf(size)),
					null,
					getResources().getString(R.string.give_up_uplaod),
					getResources().getString(R.string.reupload),
					new DialogBase.BottomTwoClickListener() {
						@Override
						public void onCancelClick(DialogBase dialog) {
							dialog.dismiss();
							uploadSuccess();
						}

						@Override
						public void onConfirmClick(DialogBase dialog) {
							// TODO: 2017/5/11 待确认
							uploadImages();
							dialog.dismiss();
						}
					}).show();
		} else {
			uploadSuccess();
		}
	}

	/**
	 * 上传成功,点击时出发,返回时触发
	 */
	public void uploadSuccess() {
		Intent data = new Intent();
		data.putParcelableArrayListExtra(IMAGE_BEANS, (ArrayList<ImageBean>) mImageAdapter.getSuccessBeanList());
		setResult(RESULT_OK, data);
		finish();
	}

	/**
	 * @param requestCode
	 * @param resultCode
	 * @param data
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		CLog.i(TAG, "onActivityResult");
		super.onActivityResult(requestCode, resultCode, data);
		mOnActivityResult = true;
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
				case REQUEST_IMAGE:
					ArrayList<ImageBean> newImageBeans = data.getParcelableArrayListExtra(PhotoSelectorActivity.EXTRA_COMPRESSED_BEANS);
					mImageAdapter.removeAll();
					if (null == newImageBeans || newImageBeans.size() == 0) {//如果没有数据, 则清空当前adapter, 并返回
						mArguments.imageBeans.clear();
						mImageAdapter.notifyDataSetChanged();
						return;
					}
					CLog.i(TAG, "lifecycle onActivityResult newImageBeans-11->" + newImageBeans.toString());
					for (ImageBean bean : newImageBeans) {
						if (mArguments.imageBeans.contains(bean)) {
							bean.status = ImageBean.STATUS_SUCCESS;
							bean.imageId = mArguments.imageBeans.get(mArguments.imageBeans.indexOf(bean)).imageId;
						}
					}
					mArguments.imageBeans.clear();
					mArguments.imageBeans.addAll(newImageBeans);
					CLog.i(TAG, "lifecycle onActivityResult newImageBeans-22->" + newImageBeans.toString());
					mImageAdapter.addData(mArguments.imageBeans);
					mImageAdapter.notifyDataSetChanged();
					uploadImages();
					CLog.i(TAG, "onActivityResult mArguments.imageBeans-->" + mArguments.imageBeans.toString());
					CLog.i(TAG, "onActivityResult mImageAdapter.toString()-->" + mImageAdapter.toString());
					break;
				default:
					break;
			}
		}
	}

	private void uploadImages() {
		List<String> uploadList = getUploadImages();
		if (uploadList.size() == 0) {
			mUploading = false;
			return;
		}
		mUploading = true;
		mPresenter.uploadImages(getUploadImages(), getImageType());
	}

	private void uploadSingleImage() {
		if (mUploadImage.size() > 0) {
			String filePath = mUploadImage.get(0);
			CLog.i(TAG, "上传图片-->" + filePath);
			mPresenter.uploadImage(filePath, getImageType());
		}
	}

	private ArrayList<String> getNewPaths(ArrayList<ImageBean> imageBeans) {
		ArrayList<String> newPaths = new ArrayList<>();
		for (ImageBean imageBean : imageBeans) {
			newPaths.add(imageBean.newPath);
		}
		return newPaths;
	}

	/**
	 * 获取待上传的图片(已选择的图片-已上传的图片)
	 *
	 * @return
	 */
	public List<String> getUploadImages() {//获取待上传的图片(已选择的图片-已上传的图片)
		mUploadImage.clear();
		List<String> files = mImageAdapter.getNeedUploadPath();
		mUploadImage.addAll(files);
		mImageAdapter.notifyDataSetChanged();
		CLog.i(TAG, "待上传图片->" + files.size());
		return files;
	}

	public String getImageType() {
		return mArguments.imageType;
	}

	/**
	 * 上传照片成功回调
	 *
	 * @param filePath
	 * @param fileName
	 * @param imageId
	 */
	@Override
	public void onUploadImage(String filePath, String fileName, String imageId) {//批量上传返回修改-需最后一张上传反馈之后再dismissLoading
		mUploadImage.remove(filePath);
		CLog.i(TAG, "上传图片成功回调--filePath=" + filePath + ";fileName=" + fileName + ";imageId" + imageId);
		mImageAdapter.changeStatus(filePath, ImageBean.STATUS_SUCCESS, imageId);
		mArguments.imageBeans.clear();
		mArguments.imageBeans.addAll(mImageAdapter.getDataSet());
		mImageAdapter.notifyDataSetChanged();
		CLog.i(TAG, "上传图片成功回调--mUploadImage.size()=" + mUploadImage.size());
		if (mUploadImage.size() == 0) {
			mUploading = false;
		} else {
			uploadSingleImage();
		}
	}

	/**
	 * 上传照片失败
	 *
	 * @param filePath
	 * @param tips
	 */
	@Override
	public void onUploadImageFailure(String filePath, String tips) {
		mUploadImage.remove(filePath);
		CLog.i(TAG, "上传图片失败回调--filePath=" + filePath + ";tips=" + tips);
		mImageAdapter.changeStatus(filePath, ImageBean.STATUS_FAIL, "");
		mArguments.imageBeans.clear();
		mArguments.imageBeans.addAll(mImageAdapter.getDataSet());
		mImageAdapter.notifyDataSetChanged();
		CLog.i(TAG, "上传图片失败回调--mUploadImage.size()=" + mUploadImage.size());
		if (mUploadImage.size() == 0) {
			mUploading = false;
		} else {
			uploadSingleImage();
		}
	}

	/**
	 * 取消上传照片
	 *
	 * @param filePath
	 * @param tips
	 */
	@Override
	public void onUploadImageCancel(String filePath, String tips) {
		if (mUploadImage.contains(filePath)) {
			CLog.i(TAG, "取消上传图片回调--filePath=" + filePath + ";tips=" + tips);
			mImageAdapter.changeStatus(filePath, ImageBean.STATUS_FAIL, "");
			mArguments.imageBeans.clear();
			mArguments.imageBeans.addAll(mImageAdapter.getDataSet());
			mImageAdapter.notifyDataSetChanged();
			CLog.i(TAG, "取消上传图片回调--mUploadImage.size()=" + mUploadImage.size());
			mUploadImage.remove(filePath);
			if (mUploadImage.size() == 0) {
				mUploading = false;
			} else {
				uploadSingleImage();
			}
		}
	}

	@Override
	public void onAddClick() {
		if (!hasWriteStoragePermission(mPermissionRequestCodeExternalStorage)) {
			return;
		}
		if (mUploading) {
			showToast(R.string.exit_toast_uploading);
			return;
		}
		CLog.i(TAG, "end");
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			ImageSelectArguments arguments = new ImageSelectArguments();
			arguments.showCamera = true;
			arguments.selectMode = PhotoSelectorActivity.SELECT_MODE_MULTI;
			arguments.remainCount = mArguments.remainCount;
			arguments.maxCount = mArguments.maxCount;
			arguments.selectedImages = mImageAdapter.getOriginalPathList();
			arguments.compressedImages = (ArrayList<ImageBean>) mImageAdapter.getDataSet();
			PhotoSelectorActivity.startForResult(this, arguments, REQUEST_IMAGE);
		}
	}

	@Override
	protected void permissionsAllGrantedSuccess(int requestCode) {
		if (requestCode == mPermissionRequestCodeExternalStorage){
			onAddClick();
		}
	}

	public ArrayList<String> getOriginalPaths() {
		List<String> selectedPaths = mImageAdapter.getPathList();
		ArrayList<String> selectedOriginalPaths = new ArrayList<>();
		for (String path : selectedPaths) {
			for (ImageBean imageBean : mArguments.imageBeans) {
				if (path.equals(imageBean.newPath)) {
					selectedOriginalPaths.add(imageBean.originalPath);
					break;
				}
			}
		}
		return selectedOriginalPaths;
	}

	@Override
	public void onDelClick(String path) {
		if (mUploading) {
			showToast(R.string.exit_toast_uploading);
			return;
		}
		ImageBean delBean = new ImageBean(path, path);
		mImageAdapter.getDataSet().remove(delBean);
		mArguments.imageBeans.clear();
		mArguments.imageBeans.addAll(mImageAdapter.getDataSet());
		mImageAdapter.notifyDataSetChanged();
	}

	@Override
	public void onReClickUpload(String path) {
		if (mUploading) {
			showToast(R.string.exit_toast_uploading);
			return;
		}
		CLog.i(TAG, "上传失败的图片-->" + mImageAdapter.getFailPathList().toString());
		uploadImages();
	}

	@Override
	public void onReviewClick(int position) {
		if (mUploading) {
			showToast(R.string.exit_toast_uploading);
			return;
		}
		ArrayList<String> picUrls = new ArrayList<>();
		picUrls.addAll(mImageAdapter.getPathList());
		PhotoViewActivity.start(this, picUrls, position, false);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		CLog.i(TAG, "lifecycle onRestoreInstanceState");
		readBundle(savedInstanceState);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		CLog.i(TAG, "lifecycle onSaveInstanceState");
		CLog.i(TAG, "lifecycle onSaveInstanceState imageBeans=" + mArguments.imageBeans.toString());
		outState.putParcelable(UPLOAD_ARGUMENTS, mArguments);
		outState.putBoolean(UPLOADING_FLAG, mUploading);
	}
}
